﻿using System;
using System.IO;
using System.Web.Mvc;
using BookShop.BLL;
using BookShop.DTO;
using BookShop.Library.Constant;
using BookShop.Library.Common;
using HTN.Library;
using PagedList;

namespace BookShop.Admin.Controllers
{
    public class AuthorController : Controller
    {
        public ActionResult Add()
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.AuthorWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(string name, string birthdate, string biography)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.AuthorWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var pictureUrl = string.Empty;
            if (Request.Files.Count > 0)
            {
                var picture = Request.Files["picture"];
                var physicalPath = Path.Combine(CommonFunction.GetConfigValue("UploadPhysicalPath"), "Picture\\Author\\");
                var virtualPath = Utility.UrlCombine("/Upload", "Picture/Author/");
                if (picture != null && !string.IsNullOrWhiteSpace(picture.FileName))
                {
                    var newFileName = Path.GetFileNameWithoutExtension(Utility.UnicodeToKoDau(picture.FileName.Trim(' ').ToLower()))
                                      + DateTime.Now.Ticks + Path.GetExtension(picture.FileName);
                    var resultPicture = Utility.UploadFile(picture.InputStream, physicalPath, newFileName, false);
                    if (!resultPicture)
                    {
                        TempData[AlertMessage.TempDataKey] = AlertMessage.FailedToUploadFile;
                    }
                    pictureUrl = Utility.UrlCombine(virtualPath, newFileName);
                }
            }
            var addResult = AuthorService.Add(name, birthdate, biography, pictureUrl);
            if (addResult != null)
            {
                return RedirectToAction("Detail", new { authorId = addResult.Id });
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.ErrorOccurs;
            ViewBag.AddName = name ?? string.Empty;
            ViewBag.AddBirthdate = birthdate ?? string.Empty;
            ViewBag.AddBiography = biography ?? string.Empty;
            return View();
        }

        public ActionResult Delete(int authorId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.AuthorWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var deleteResult = AuthorService.Delete(authorId);
            if (!deleteResult)
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.ErrorOccurs;
            }
            return RedirectToAction("List");
        }

        public ActionResult Detail(int authorId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.AuthorRead))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var author = AuthorService.GetById(authorId);
            if (author != null)
            {
                return View(author);
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.NotFoundObject;
            return RedirectToAction("List");
        }

        public ActionResult Edit(int authorId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.AuthorWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var author = AuthorService.GetById(authorId);
            if (author != null)
            {
                return View(author);
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.NotFoundObject;
            return RedirectToAction("List");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int authorId, string name, string birthdate, string biography, int status)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.AuthorWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var pictureUrl = string.Empty;
            if (Request.Files.Count > 0)
            {
                var picture = Request.Files["picture"];
                var physicalPath = Path.Combine(CommonFunction.GetConfigValue("UploadPhysicalPath"), "Picture\\Author\\");
                var virtualPath = Utility.UrlCombine("/Upload", "Picture/Author/");
                if (picture != null && !string.IsNullOrWhiteSpace(picture.FileName))
                {
                    var newFileName = Path.GetFileNameWithoutExtension(Utility.UnicodeToKoDau(picture.FileName.Trim(' ').ToLower()))
                                      + DateTime.Now.Ticks + Path.GetExtension(picture.FileName);
                    var resultPicture = Utility.UploadFile(picture.InputStream, physicalPath, newFileName, false);
                    if (!resultPicture)
                    {
                        TempData[AlertMessage.TempDataKey] = AlertMessage.FailedToUploadFile;
                    }
                    pictureUrl = Utility.UrlCombine(virtualPath, newFileName);
                }
            }
            var editResult = AuthorService.Update(authorId, name, birthdate, biography, pictureUrl, status);
            if (editResult != null)
            {
                return RedirectToAction("Detail", new { authorId });
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.ErrorOccurs;
            return RedirectToAction("List");
        }

        [ValidateInput(false)]
        public ActionResult List(int? authorId, string name, string fromBirthdate, string toBirthdate, int? status,
            int page = 1, int pageSize = 10)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.AuthorRead))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("Index", "Home");
            }
            int totalRow;
            var model = AuthorService.Search(authorId, name, fromBirthdate, toBirthdate, string.Empty, status, page, pageSize,
                out totalRow);
            ViewBag.SearchId = authorId.ToString();
            ViewBag.SearchName = name ?? string.Empty;
            ViewBag.SearchFromBirthdate = fromBirthdate ?? string.Empty;
            ViewBag.SearchToBirthdate = toBirthdate ?? string.Empty;
            ViewBag.SearchStatus = status.ToString();
            ViewBag.PageList = new StaticPagedList<Author>(model, page, pageSize, totalRow);
            ViewBag.RecordsCount = "Tổng số bản ghi: " + totalRow;
            return View(model);
        }

    }
}
